﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using IFactory;
using System.IO;

public partial class Month_NoShenHe : System.Web.UI.Page
{
    QuarterDateManager dllQuarterDateManager = new QuarterDateManager();
    MonthDateManager dllMonthDateManager = new MonthDateManager();
    MonthPlanManager dllMonthPlanManager = new MonthPlanManager();
    UserInfoManager dllUserInfoManager = new UserInfoManager();
    VerifyCircuitManager dllVerifyCircuitManager = new VerifyCircuitManager();
    IBussinessLogic dllUserInfo = new UserInfoManager();
    Authentication dllAuthentication = new Authentication();
    Model.UserInfo objUserInfo = new Model.UserInfo();
    DataTable _powerTable = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();

        this.btnOk.Visible = false;
        
        this.ckbAllSelect.Visible = false;
        _powerTable = dllAuthentication.getPower(objUserInfo.UserName, "已评估月计划");
        for (int i = 0; i < _powerTable.Rows.Count; i++)
        {
            if (_powerTable.Rows[i]["PowerName"].ToString() == "新建")
            {
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "删除")
            {
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "查看")
            {
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "修改")
            {
                this.btnOk.Visible = false;
            }
        }

        if (!IsPostBack)
        {
            #region 弹出提醒
            PopupManager dllPopupManager = new PopupManager();
            string _info = dllPopupManager.getPopupInfo();
            if (_info.Length > 0)
            {
                ShowMessage(_info);
            }
            #endregion
            bindDropDownList(this.drpYear);
            bindDropDownList(this.drpQuarterDate);
        }
    }

    /// <summary>
    /// 弹出小窗体事件
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessage(string msg)
    {
        EeekSoft.Web.PopupWin pop = new EeekSoft.Web.PopupWin();
        this.Controls.Add(pop);
        pop.Text = msg;
        pop.Message = msg;
        pop.Title = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();
        pop.WindowScroll = true;
        pop.HideAfter = 99999999;
        pop.DockMode = EeekSoft.Web.PopupDocking.BottomLeft;
        pop.OffsetX = int.Parse(Session["_width"].ToString()) - 338;
        pop.ActionType = EeekSoft.Web.PopupAction.MessageWindow;
        pop.OffsetY = 1;
        pop.Width = 220;
        pop.Height = 170;
    }

    /// <summary>
    /// 绑定所有的dropdownlist
    /// </summary>
    /// <param name="_drp"></param>
    void bindDropDownList(DropDownList _drp)
    {
        //年份绑定
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem _li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(_li);
            }
            //根据系统日期自动绑定到当前年份
            //string _year = DateTime.Now.Year.ToString();
            //this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));
            //根据系统当前日期查找到对应的年周期
            DataTable _year = dllQuarterDateManager.getQuarterDate();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year.Rows[0][2].ToString()));

        }

        //绑定年计划周期
        if (_drp.Equals(this.drpQuarterDate))
        {
            object[] _value = new object[1];
            _value[0] = this.drpYear.SelectedValue;
            DataTable _quarter = dllQuarterDateManager.get(QuarterDateManager.field.QuarterYear.ToString(), _value);
            if (_quarter.Rows.Count != 0)
            {
                this.drpQuarterDate.DataSource = _quarter;
                this.drpQuarterDate.DataTextField = "QuarterName";
                this.drpQuarterDate.DataValueField = "Quarter_Id";
                this.drpQuarterDate.DataBind();
                #region dropdownlist显示系统所对应的当前年周期
                //根据系统当前日期查找到对应的年周期
                DataTable _quartertime = dllQuarterDateManager.getQuarterDate();
                //如果查到结果（结果只有一条）

                if (_quartertime.Rows.Count == 1)
                {
                    this.drpQuarterDate.SelectedIndex = this.drpQuarterDate.Items.IndexOf(this.drpQuarterDate.Items.FindByText(_quartertime.Rows[0][1].ToString()));
                    this.drpQuarterDate.DataSource = _quartertime;
                    this.drpQuarterDate.DataTextField = "QuarterName";
                    this.drpQuarterDate.DataValueField = "Quarter_Id";
                }
                #endregion
                bindDropDownList(this.drpMonthDate);
            }
            else
            {
                ListItem _li = new ListItem("无年周期");
                this.drpQuarterDate.Items.Clear();
                this.drpQuarterDate.Items.Add(_li);
                bindDropDownList(this.drpMonthDate);
            }


        }

        //绑定月计划周期
        if (_drp.Equals(this.drpMonthDate))
        {

            object[] _value = new object[2];
            _value[0] = this.drpYear.SelectedValue;
            _value[1] = this.drpQuarterDate.SelectedItem.Text;
            DataTable _month = dllMonthDateManager.get(MonthDateManager.field.QuarterName.ToString(), _value);
            if (_month.Rows.Count != 0)
            {
                this.drpMonthDate.DataSource = _month;
                this.drpMonthDate.DataTextField = "MonthName";
                this.drpMonthDate.DataValueField = "Month_Id";
                this.drpMonthDate.DataBind();
                #region 根据系统当前日期绑定到当前月周期
                DataTable _monthtime = dllMonthDateManager.getMonthDate();
                if (_monthtime.Rows.Count == 1)
                {
                    this.drpMonthDate.SelectedIndex = this.drpMonthDate.Items.IndexOf(this.drpMonthDate.Items.FindByText(_monthtime.Rows[0][3].ToString()));
                    this.drpMonthDate.DataSource = _monthtime;
                    this.drpMonthDate.DataTextField = "MonthName";
                    this.drpMonthDate.DataValueField = "Month_Id";

                }
                #endregion
                bindNoShenHe();
            }
            else
            {
                ListItem _li = new ListItem("无月周期");
                this.drpMonthDate.Items.Clear();
                this.drpMonthDate.Items.Add(_li);
                this.gdvNoShenHeMonthPlan.DataSource = new DataTable();
                this.gdvNoShenHeMonthPlan.DataBind();
            }

        }

    }

    /// <summary>
    /// 根据逗号换行事件
    /// </summary>
    void wrapByComma(GridView _gridView, int _rowIndex, int _cells)
    {
        string _content = _gridView.Rows[_rowIndex].Cells[_cells].Text;
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&lt;br&gt;", "<br>");
        //_gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&gt;", ">");
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _gridView.Rows[_rowIndex].Cells[_cells].Text.Replace(",", "<br>");


    }
    /// <summary>
    /// 绑定gridview
    /// </summary>
    void bindNoShenHe()
    {
        object[] _value = new object[2];
        Model.UserInfo objUserInfo = new Model.UserInfo();
        _value[1] = objUserInfo.UserName;
        _value[0] = Convert.ToInt32(this.drpMonthDate.SelectedItem.Value);
        DataView dv = new DataView(dllMonthPlanManager.getMonthPlanEvaluated(_value));
        dv.Sort = "MonthPlanSortId";
        this.gdvNoShenHeMonthPlan.DataSource = dv;
        this.gdvNoShenHeMonthPlan.DataBind();
        
        for (int i = 0; i < gdvNoShenHeMonthPlan.Rows.Count; i++)
        {
            wrapByComma(this.gdvNoShenHeMonthPlan, i, 8);
            
            //文件下载，判断如果下载了就显示《下载按钮》 反之 就显示“无下载”
            if (gdvNoShenHeMonthPlan.DataKeys[i]["AttachmentPath"].ToString().Length == 0)
            {
                Button _btn = (Button)gdvNoShenHeMonthPlan.Rows[i].Cells[12].FindControl("btnDownLoad");
                _btn.Visible = false;
                Label _lbl = (Label)gdvNoShenHeMonthPlan.Rows[i].Cells[12].FindControl("lblAlert");
                _lbl.Visible = true;
                _lbl.Text = "无下载";
            }
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text.Replace("&", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text.Replace("nbsp;", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].Text.Replace("amp;", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text.Replace("&", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text.Replace("nbsp;", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[13].Text.Replace("amp;", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text.Replace("&", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text.Replace("nbsp;", "");
            this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text = this.gdvNoShenHeMonthPlan.Rows[i].Cells[9].Text.Replace("amp;", "");
        }

    }
    /// <summary>
    /// 通过事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        //根据评估人查询当前用户的待审月计划
        Model.UserInfo objUserInfo = new Model.UserInfo();
        object[] _user = new object[1];
        _user[0] = objUserInfo.UserName;
        DataTable _userInfo = dllUserInfo.get(UserInfoManager.field.UserName.ToString(), _user);
        if (_userInfo.Rows.Count > 0)
        {
            int _count = 0;
            List<object[]> _valueList = new List<object[]>();
            for (int i = 0; i < this.gdvNoShenHeMonthPlan.Rows.Count; i++)
            {
                CheckBox ckb = (CheckBox)this.gdvNoShenHeMonthPlan.Rows[i].Cells[0].FindControl("ckbSelect");
                if (ckb.Checked == true)
                {
                    object[] _value = new object[2];
                    _value[0] = Convert.ToInt32(this.gdvNoShenHeMonthPlan.DataKeys[i]["MonthPlanId"].ToString());
                    _value[1] = _userInfo.Rows[0]["RealName"].ToString();
                    _valueList.Add(_value);
                    _count++;
                }
            }
            if (_count == 0)
            {
                Utility.HttpHelp.alert("请至少选择一个月计划", Page);
                return;
            }
            if (_valueList.Count > 0)
            {
                //修改发送状态为3，提交审核
                int result = dllMonthPlanManager.editWithTransaction(MonthPlanManager.field.VerifyPeople.ToString(), _valueList);
                if (result == 0)
                {
                    Utility.Error.RedirectErrorPage("提交月计划审核未成功，请重试！");
                }
                else
                {
                    Response.Redirect("NoShenHe.aspx");
                }
            }
        }
        else
        {
            Utility.Error.RedirectErrorPage("提交月计划审核未成功，请重试！");
        }
    }
    /// <summary>
    /// 退回事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        int i = 0;
        Button bt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        object[] _value = new object[2];
        _value[0] = Convert.ToInt32(this.gdvNoShenHeMonthPlan.DataKeys[i]["MonthPlanId"].ToString());
        _value[1] = ((TextBox)this.gdvNoShenHeMonthPlan.Rows[i].Cells[11].FindControl("txtCheckNote")).Text;
        //修改年计划发送状态为0，填写checknote字段内容（追加）
        int result = dllMonthPlanManager.edit(MonthPlanManager.field.CheckNote.ToString(), _value);
        if (result == 0)
        {
            Utility.Error.RedirectErrorPage("退回月计划未成功，请重试！");
        }
        else
        {
            Response.Redirect("NoShenHe.aspx");
        }
    }
    /// <summary>
    /// 全选事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ckbAllSelect_CheckedChanged(object sender, EventArgs e)
    {
        if (ckbAllSelect.Checked == true)
        {
            for (int i = 0; i < this.gdvNoShenHeMonthPlan.Rows.Count; i++)
            {
                CheckBox ckb = (CheckBox)this.gdvNoShenHeMonthPlan.Rows[i].Cells[0].FindControl("ckbSelect");
                ckb.Checked = true;
            }
        }
        else
        {
            for (int i = 0; i < this.gdvNoShenHeMonthPlan.Rows.Count; i++)
            {
                CheckBox ckb = (CheckBox)this.gdvNoShenHeMonthPlan.Rows[i].Cells[0].FindControl("ckbSelect");
                ckb.Checked = false;
            }
        }
    }
    /// <summary>
    /// 分页事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gdvNoShenHeMonthPlan_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gdvNoShenHeMonthPlan.PageIndex = e.NewPageIndex;
        bindNoShenHe();
    }
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {

        bindDropDownList(this.drpQuarterDate);
        bindDropDownList(this.drpMonthDate);
        if (this.drpMonthDate.Text != "无月周期")
        {
            bindNoShenHe();
        }
        else
        {
            this.gdvNoShenHeMonthPlan.DataSource = new DataTable();
            this.gdvNoShenHeMonthPlan.DataBind();

        }
    }
    protected void drpQuarterDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDropDownList(this.drpMonthDate);
    }
    protected void drpMonthDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindNoShenHe();
    }

    /// <summary>
    /// 查看流程
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnVerifyCircuit_Click(object sender, EventArgs e)
    {
        int _count = 0;
        string _url = "";
        int _monthId = 0;
        for (int i = 0; i < this.gdvNoShenHeMonthPlan.Rows.Count; i++)
        {
            CheckBox chk = (CheckBox)this.gdvNoShenHeMonthPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (chk.Checked == true)
            {
                _count++;
                _monthId = Convert.ToInt32(this.gdvNoShenHeMonthPlan.DataKeys[i]["MonthPlanId"].ToString());

            }
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
        if (_count == 1)
        {
            _url = "../WebCommon/VerifyCircruitDisplay.aspx?PlanId=" + _monthId + "&PlanType=2";
            Page.RegisterStartupScript("windowOpen",
               "<script language=javascript>window.open('" + _url + "','newwindow','height=150,width=550,top=250,left=300,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
        }

    }

    /// <summary>
    /// 查看附件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDownLoad_Click(object sender, EventArgs e)
    {

        int i = 0;
        Button btt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)btt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        //读取隐藏地址列
        string path = this.gdvNoShenHeMonthPlan.DataKeys[i]["AttachmentPath"].ToString();
        FileDownload(path);
        
        //Utility.HttpHelp.DownloadFile(path);
    }

    ///   <summary>   
    ///   文件下载   
    ///   </summary>   
    ///   <param   name="FullFileName"></param>   
    private void FileDownload(string strFileName)
    {

        FileInfo DownloadFile = new FileInfo(strFileName);
        if (!DownloadFile.Exists)
        {
            Utility.HttpHelp.alert("无附件,请与管理员联系", Page);
            return;
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName.Substring(strFileName.LastIndexOf('\\') + 1), System.Text.Encoding.UTF8));
        // Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

        Response.WriteFile(DownloadFile.FullName);
        Response.Flush();
        Response.End();

    }
}
